<template>
	<div class="login">
		<h2>用户登录</h2>
		<van-form @submit="onSubmit">
			<van-cell-group inset>
				<van-field
					v-model="username"
					name="username"
					label="用户名"
					placeholder="用户名"
					:rules="[{ required: true, message: '请填写用户名' }]"
				/>
				<van-field
					v-model="password"
					type="password"
					name="password"
					label="密码"
					placeholder="密码"
					:rules="[{ required: true, message: '请填写密码' }]"
				/>
			</van-cell-group>
			<div style="margin: 16px;">
				<van-button round block type="primary" native-type="submit">提交</van-button>
			</div>
		</van-form>
	</div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { postLogin } from '@/api'
import { Notify } from 'vant'
import { useStore } from 'vuex';
const store = useStore()
const username = ref('')
const password = ref('')

const onSubmit = async (value: any) => {
	const resp = await postLogin({ username: username.value, password: password.value })
	const { code, data, mess } = resp.data

	if (code === 200) {
		Notify({ type: 'success', message: '登录成功, 欢迎' + data.username, onClose() { history.back() } })
		store.commit('setUser', { isLogin: true, token: data.token, username: data.username })
	} else {
		Notify({ type: 'danger', message: mess })
	}
}
</script>

<style>
.login {
	position: fixed;
	top: 40%;
	transform: translateY(-50%);
}

h2 {
	text-align: center;
}
</style>